<template>
  <a-modal v-model:visible="visible" :title="isEdit ? '修改工序' : '新增工序'" @ok="handleOk" @cancel="handleCancel"
    :confirmLoading="confirmLoading" destroyOnClose>
    <a-form ref="formRef" :model="formData" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
      <a-form-item label="执行顺序" name="executeProcesses">
        <a-input v-model:value="formData.executeProcesses" placeholder="请输入执行顺序" style="width: 100%" />
      </a-form-item>
      <a-form-item label="工序名称" name="processesName">
        <a-input v-model:value="formData.processesName" placeholder="请输入工序名称" style="width: 100%" />
      </a-form-item>
      <a-form-item label="负责人员" name="leader" required>
        <a-select v-model:value="formData.leader" show-search placeholder="请选择负责人" :filter-option="false"
          :show-arrow="false" :not-found-content="null" @search="handleSearch" @change="handleSelect">
          <a-select-option v-for="item in productOptions" :key="item.id" :value="item.name">
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="计费方式" name="billingMethod">
        <a-select v-model:value="formData.billingMethod" @change="handleBillingMethodChange">
          <a-select-option value="计时">计时</a-select-option>
          <a-select-option value="计件">计件</a-select-option>
          <a-select-option value="固定工资">固定工资</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item v-if="showWages" label="工价" name="wages">
        <a-input-number v-model:value="formData.wages" placeholder="请输入工价" style="width: 100%" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, computed } from 'vue';
import type { FormInstance } from 'ant-design-vue';
import { message } from 'ant-design-vue';
import { bomProductApi } from '/@/api/base-data/product/bom-product';
import { userApi } from '/@/api/system/user';

export default defineComponent({
  name: 'AddProcess',
  emits: ['confirm', 'refresh'],
  setup(props, { emit }) {
    const visible = ref(false);
    const confirmLoading = ref(false);
    const formRef = ref<FormInstance>();
    const isEdit = ref(false);
    const editId = ref<string | null>(null);
    const formData = reactive({
      executeProcesses: '',
      processesName: '',
      leader: '',
      billingMethod: '计时', // 默认值为"计时"
      wages: '',
      productId: '',
    });
    // 表单验证规则
    const rules = {
      executeProcesses: [{ required: true, message: '请输入执行顺序' }, { max: 100, message: '最大长度为100个字符' }],
      processesName: [{ required: true, message: '请输入工序名称' }, { max: 100, message: '最大长度为100个字符' }],
      leader: [{ required: true, message: '请输入负责人员' }, { max: 100, message: '最大长度为100个字符' }],
      billingMethod: [{ required: true, message: '请选择计费方式' }],
      wages: [{ required: false, message: '请输入工价' }],
    };
    // 是否显示工价
    const showWages = computed(() => formData.billingMethod !== '固定工资');
    // 计费方式改变
    const handleBillingMethodChange = (value: string) => {
      if (value === '固定工资') {
        formData.wages = '';
      }
    };
    // 负责人选项
    const productOptions = ref<any[]>([]);
    // 搜索负责人
    const handleSearch = async (value: string) => {
      try {

        //负责人接口，使用时交换注释即可
        // const res = await userApi.queryAllUserNoPage(value);
        const res = {
          datas: [
            {
              id: 1,
              name: '张三',
            },
            {
              id: 2,
              name: '李四',
            }
          ]
        }
        if (res && res.datas) {
          productOptions.value = res.datas.map(item => ({
            id: item.id,
            name: item.name,
          }));
        }
        console.log("====================.--------", res);
      } catch (error) {
        console.error('查询负责人失败:', error);
        productOptions.value = [];
      }
    };
    // 选择负责人
    const handleSelect = (value: string) => {
      const selectedProduct = productOptions.value.find(item => item.name === value);
      console.log(selectedProduct)
      if (selectedProduct) {
        formData.leader = selectedProduct.name;
      }
    };
    // 初始化负责人选项
    const initProductOptions = () => {
      handleSearch('');
    };
    // 新增或修改，提交弹框
    const handleOk = async () => {
      try {
        await formRef.value?.validate();
        confirmLoading.value = true;
        const apiCall = isEdit.value
          ? bomProductApi.updateProcess({ ...formData, id: editId.value })
          : bomProductApi.addProcess(formData);
        await apiCall;
        message.success(isEdit.value ? '修改成功' : '添加成功');
        emit('refresh');
        handleCancel();
      } catch (error) {
        console.error('提交失败:', error);
        message.error('提交失败，请检查输入或稍后重试');
      } finally {
        confirmLoading.value = false;
      }
    };

    const handleCancel = () => {
      visible.value = false;
      formRef.value?.resetFields();
      isEdit.value = false;
      editId.value = null;
      Object.assign(formData, {
        executeProcesses: '',
        processesName: '',
        leader: '',
        billingMethod: '计时',
        wages: '',
        productId: '',
      });
    };

    const openDialog = (record?: any) => {
      console.log("=============>--------------------", record)
      visible.value = true;
      initProductOptions();
      if (Object.prototype.toString.call(record) === '[object Object]') {
        isEdit.value = true;
        editId.value = record.id;
        console.log("=============>", record.id)
        Object.assign(formData, {
          executeProcesses: record.executeProcesses,
          processesName: record.processesName,
          leader: record.leader,
          billingMethod: record.billingMethod,
          wages: record.wages,
          productId: record.productId,
        });
      } else {
        isEdit.value = false;
        editId.value = null;
        Object.assign(formData, {
          productId: record,
          executeProcesses: '',
          processesName: '',
          leader: '',
          billingMethod: '计时',
          wages: '',
        });
      }
    };

    return {
      visible,
      confirmLoading,
      formRef,
      formData,
      rules,
      showWages,
      handleBillingMethodChange,
      handleOk,
      handleCancel,
      openDialog,
      isEdit,
      productOptions,
      initProductOptions,
      handleSearch,
      handleSelect,
    };
  },
});
</script>

<style lang="less" scoped>
:deep(.ant-select-item-option-content) {
  display: flex;
  justify-content: space-between;
  align-items: center;

  span {
    color: #999;
    font-size: 12px;
  }
}
</style>
